rm(list=ls())
library(readstata13)
library(mediation)
library(dplyr)
library(stargazer)

#this data includes only elections and variables used in Models 5 & 6 of main analysis, otherwise errors occur
election <- read.dta13("mediationII.dta")

#french colony & fraud
y <- glm.nb(postviolence ~ frenchcol + seriousfraud + nelda45 + electioncountry + lastconflict + Nelda13 + logdp + logpop + repression + latentm_lag + xpolity + naturalresources, data=election, control=glm.control(maxit=100))
m <- glm(seriousfraud ~ frenchcol + lastconflict + nelda45 + electioncountry + Nelda13 + logdp + logpop + repression + xpolity + latentm_lag + naturalresources, family=binomial(link=logit), data=election)

french <- mediate(m, y, sims = 1000, treat = "frenchcol", mediator = "seriousfraud", cluster=election$country)

plot.mediate(french)

#us military aid & fraud
y <- glm.nb(postviolence ~ lnusmil_lagged + lnuseco_lagged + seriousfraud + nelda45 + electioncountry + repression + lastconflict + Nelda13 + logdp + logpop + latentm_lag + xpolity + naturalresources, data=election, control=glm.control(maxit=1000))
m <- glm(seriousfraud ~ lnusmil_lagged + lnuseco_lagged + lastconflict + nelda45 + electioncountry + repression + Nelda13 + logdp + logpop + latentm_lag + xpolity + naturalresources, family=binomial(link=logit), data=election)

us <- mediate(m, y, sims = 1000, treat = "lnusmil_lagged", mediator = "seriousfraud", control.value = 0, treat.value = 21, cluster=election$country)

plot.mediate(us)

#french colony & repression 

y <- glm.nb(postviolence ~ frenchcol + seriousfraud + nelda45 + electioncountry + lastconflict + Nelda13 + logdp + logpop + repression + latentm_lag + xpolity + naturalresources, data=election, control=glm.control(maxit=100))
m <- glm(repression ~ frenchcol + lastconflict + nelda45 + electioncountry + Nelda13 + logdp + logpop + seriousfraud + xpolity + latentm_lag + naturalresources, family=binomial(link=logit), data=election)

french <- mediate(m, y, sims = 1000, treat = "frenchcol", mediator = "repression", cluster=election$country)

plot.mediate(french)

#US military aid & repression

y <- glm.nb(postviolence ~ lnusmil_lagged + lnuseco_lagged + seriousfraud + Nelda13 + repression + nelda45 + electioncountry + lastconflict + logdp + logpop + latentm_lag + xpolity + naturalresources, data=election, control=glm.control(maxit=1000))
m <- glm(repression ~ lnusmil_lagged + lnuseco_lagged + lastconflict + seriousfraud + Nelda13 + nelda45 + electioncountry + logdp + logpop + latentm_lag + xpolity + naturalresources, family=binomial(link=logit), data=election, control=glm.control(maxit=1000))

us <- mediate(m, y, sims = 1000, treat = "lnusmil_lagged", mediator = "repression", cluster=election$country)

plot.mediate(us)



